import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {},
    isLoggedIn: false,
    isPremium: false,
    credits: 100,
  }),
  
  getters: {
    getUserInfo: (state) => state.userInfo,
    getIsLoggedIn: (state) => state.isLoggedIn,
    getLoginStatus: (state) => state.isLoggedIn,
    getPremiumStatus: (state) => state.isPremium,
    getCredits: (state) => state.credits,
    getUserName: (state) => state.userInfo.nickname || state.userInfo.phone || '',
    getUserPhone: (state) => state.userInfo.phone || '',
  },
  
  actions: {
    login(userInfo) {
      this.userInfo = userInfo || {}
      this.isLoggedIn = true
    },
    
    logout() {
      this.userInfo = {}
      localStorage.removeItem('user-token')
      this.isLoggedIn = false
    },
    
    setUserInfo(userInfo) {
      this.userInfo = userInfo || {}
      this.isLoggedIn = true
    },
    
    updatePremiumStatus(status) {
      this.isPremium = status
    },
    
    updateCredits(amount) {
      this.credits = amount
    },
    
    addCredits(amount) {
      this.credits += amount
    },
    
    useCredits(amount) {
      if (this.credits >= amount) {
        this.credits -= amount
        return true
      }
      return false
    }
  },
  
  persist: {
    key: 'user-store',
    storage: localStorage,
  },
})
